# -*- encoding: utf8 -*-
from contextlib import contextmanager
from datetime import datetime

from flask_sqlalchemy import SQLAlchemy as _SQLALchemy
from sqlalchemy import Column, SmallInteger, String


class SQLAlchemy(_SQLALchemy):
    @contextmanager
    def auto_commit(self):
        try:
            yield
            self.session.commit()
        except Exception as e:
            db.session.rollback()  # 回滚事务
            raise e


db = SQLAlchemy()


class Base(db.Model):
    __abstract__ = True
    create_time = Column('create_time', String(30))
    status = Column(SmallInteger, default=1)

    def __init__(self):
        self.create_time = datetime.now().strftime('%Y-%m-%d %H:%M:%S')

    # 体现python动态语言的特性  将dict中与db中有相同key时，写入db
    def set_attrs(self, attrs_dict):
        for k, v in attrs_dict.items():
            if hasattr(self, k) and k != 'id':
                setattr(self, k, v)
